package com.cola.springmvc.controller;

import com.cola.springmvc.dao.UserDao;
import com.cola.springmvc.exception.LackParamException;
import com.cola.springmvc.pojo.Address;
import com.cola.springmvc.pojo.User;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.annotation.SessionScope;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import javax.sound.midi.Soundbank;
import java.io.File;
import java.io.IOException;
import java.sql.SQLOutput;
import java.util.Collection;
import java.util.Map;
import java.util.UUID;

/**
 * @Grup:com.cola.springmvc.controller
 * @Auther:cola
 * @Data:2021/4/25-2021-04-20:05
 * @version:1.0
 */

//使用原生API
//直接在Controller层的方法参数列表中添加需要的对象
@Controller
//@RequestMapping("/user")
//@SessionAttributes(value = {"user"},types = {String.class})//type设置session允许的数据类型,value设置传输的用户名变量
public class UserController {
    @Autowired
    private UserDao userDao;
    ////////////////////////////////异常处理//////////////////
    //简单异常处理
    @ExceptionHandler(LackParamException.class)//class类型处理特定类型的异常
    public ModelAndView handleException(Exception e){
        System.out.println("出现异常"+e);
        ModelAndView mv=new ModelAndView();
        mv.setViewName("error");
        mv.addObject("exception",e);
        return mv;
    }

    /*@ExceptionHandler
    public ModelAndView handleException(Exception e){
        System.out.println("出现异常"+e);
        ModelAndView mv=new ModelAndView();
        mv.setViewName("error");
        mv.addObject("exception",e);
        return mv;
    }*/

    /*@ExceptionHandler
    public String handleException(Exception e,Model model){
        System.out.println("出现异常"+e);
        return "error";
    }*/
    @RequestMapping("test_exception")
    public String testException(String str) throws LackParamException {
        if (StringUtils.isEmpty(str)){
            throw new LackParamException();
        }
        return "success";
    }
    ////////////////////////////////类型转换//////////////////




    ////////////////////////////////RESTful//////////////////

    @RequestMapping(value = "/users",method = RequestMethod.GET)
    public  String list(Model model){
        /*
         * @param [model]
         * @Name list
         * @return java.lang.String
         * @author cola
         * @date 2021/4/28 17:19
         * Description: //TODO 查询显示数据信息
        */
        //int a =1000/0;
        //Integer.parseInt("adf");
        Collection<User> userlist = userDao.getAll();
        model.addAttribute("userlist",userlist);
        return "user/list";
    }


    @RequestMapping(value = "/user/{id}",method = RequestMethod.DELETE)
    public  String delete(@PathVariable(value = "id")Integer id){
        /*
         * @param [id]
         * @Name delete
         * @return java.lang.String
         * @author cola
         * @date 2021/4/28 17:20
         * Description: //TODO 根据id查询数据信息
        */
        System.out.println("delete"+id);
        userDao.delete(id);
        return "redirect:/users";
    }
    @RequestMapping(value = "/user",method = RequestMethod.GET)
    public  String add(){
        /*
         * @param []
         * @Name add
         * @return java.lang.String
         * @author cola
         * @date 2021/4/28 17:20
         * Description: //TODO 添加信息user类
        */
        System.out.println("add");
        return "user/add";
    }

    @RequestMapping(value = "/user",method = RequestMethod.POST)
    public String save(User user){
        /*
         * @param [user]
         * @Name save
         * @return java.lang.String
         * @author cola
         * @date 2021/4/28 17:21
         * Description: //TODO 将数据user保存到map中
         */
        System.out.println(user);
        System.out.println("save");
        userDao.save(user);
        return "redirect:/users";
    }
    @RequestMapping(value = "/user/{id}",method = RequestMethod.GET)
    public  String edit(@PathVariable(value = "id") Integer id, Model model){
        System.out.println("edit");
        User user = userDao.get(id);
        model.addAttribute("user",user);
        return "user/edict";
    }
    @RequestMapping(value = "/user/{id}",method = RequestMethod.PUT)
    public String update(@PathVariable(value = "id") Integer id,User user){
        /*
         * @param [user]
         * @Name save
         * @return java.lang.String
         * @author cola
         * @date 2021/4/28 17:21
         * Description: //TODO 将数据user保存到map中
         */
        user.setId(id);
        userDao.save(user);
        return "redirect:/users";
    }
    @RequestMapping(value = "/saveuser",method = RequestMethod.POST)
    public String saveuser(User user){

        System.out.println(user);
        System.out.println("saveuser");
        userDao.save(user);
        return "redirect:/users";
    }
    ////////////////////////////////json和jsonp//////////////////
    @ResponseBody
    @RequestMapping(value = "/users-json",method = RequestMethod.GET)
    public  Collection<User> listjson(){
        /*
         * @param []
         * @Name listjson
         * @return java.util.Collection<com.cola.springmvc.pojo.User>
         * @author cola
         * @date 2021/5/2 13:11
         * Description: //TODO
         */
        return userDao.getAll();

    }

    /*定义jsonp环境*/
    @RequestMapping(value = "/users-jsonp",method = RequestMethod.GET)
    public  void listjson(String callback, HttpServletResponse response) throws IOException {
        Collection<User> list=userDao.getAll();
        Gson gson=new Gson();
        String json = gson.toJson(list);
        response.getWriter().println(callback+"("+json+")");
    }

    @RequestMapping(value = "/user-json",method = RequestMethod.POST)
    public String savejson(@RequestBody User user){
        /*
         * @param [user]
         * @Name save
         * @return java.lang.String
         * @author cola
         * @date 2021/4/28 17:21
         * Description: //TODO 将数据user保存到map中
         */
        System.out.println(user);
        System.out.println("savejson");
        userDao.save(user);
        return "redirect:/users";
    }
    ////////////////////////////////文件上传//////////////////
    @RequestMapping(value = "/fileupload",method = RequestMethod.POST)
    public String fileupload( String desc, MultipartFile file,Model model) throws IOException {
        System.out.println(desc);
        System.out.println(file);
        if (file!=null&&file.getOriginalFilename()!=null&&file.getOriginalFilename().length()>0){
            String filepath="E:\\upload\\";
            System.out.println("***********************************");
            String originalFilename = file.getOriginalFilename();
            System.out.println(originalFilename);
            //扩展名
            String extendsName=originalFilename.substring(originalFilename.lastIndexOf("."));
            System.out.println(extendsName);
            //文件名
            String newFilename=UUID.randomUUID().toString() + extendsName;
            System.out.println(newFilename);
            //文件路径
            File uploadFile= new File(filepath+newFilename);
            file.transferTo(uploadFile);
            model.addAttribute("filepath","/file/"+newFilename);
            return "success";
        }
        return "error";
    }


    /*@RequestMapping("/form")
    public String form(){
        System.out.println("user/form");
        return "user/form";
    }

    @RequestMapping("/edict")
    public ModelAndView edict(){
        *//*
     * @param []
     * @Name edict
     * @return org.springframework.web.servlet.ModelAndView
     * @author cola
     * @date 2021/4/26 19:11
     * Description: //TODO 自动将要传递到页面的数据注入到Model参数中
     *//*
        User user = new User();
        user.setUsername("尼玛");
        user.setPassword("12");
        user.setAge(12);
        user.setEmail("1064@");
        Address address=new Address();
        address.setProvince("兴建");
        address.setCity("建安");
        user.setAddress(address);

        ModelAndView mv=new ModelAndView();
        mv.setViewName("user/edict");
        mv.addObject("user",user);
        return mv;
    }
    @RequestMapping("/edict1")
    public String edict1(Map<String,Object> map){
        *//*
     * @param [map]
     * @Name edict1
     * @return java.lang.String
     * @author cola
     * @date 2021/4/26 19:10
     * Description: //TODO 自动将要传递到页面的数据注入到Map参数中
     *//*

        User user = new User();
        user.setUsername("此乃NBC");
        user.setPassword("123");
        user.setAge(12);
        user.setEmail("1064@");
        Address address=new Address();
        address.setProvince("兴建");
        address.setCity("建安");
        user.setAddress(address);

        map.put("user",user);
        return "
        ";
    }
    @RequestMapping("/edict2")
    public String edict2(Model model){
        *//*
     * @param [model]
     * @Name edict2
     * @return java.lang.String
     * @author cola
     * @date 2021/4/26 19:11
     * Description: //TODO 自动将要传递到页面的数据注入到map参数中
     *//*

        User user = new User();
        user.setUsername("你是嗲毛");
        user.setPassword("1234");
        user.setAge(12);
        user.setEmail("1064@");
        Address address=new Address();
        address.setProvince("兴建");
        address.setCity("建安");
        user.setAddress(address);
        System.out.println(user);
        model.addAttribute("user",user);
        model.addAttribute("strvalue","GBK998");
        model.addAttribute("intvalue",17);
        return "user/edict";
    }*/
}
